package edu.hawaii.ics.pjdb.partition_function;

import java.util.ArrayList;
import java.util.List;

import edu.hawaii.ics.pjdb.types.Tuple;

/**
 * Defines a PartitionFunction which splits the given tuples evenly among the
 * given number of partitions.
 * 
 * @author Christopher Foo
 * 
 */
public class SequentialSplit implements PartitionFunction {

    @Override
    /**
     * @param arguments arguments[0] = A String representation of an integer denoting the number of partitions to make.
     */
    public ArrayList<ArrayList<Tuple>> partition(List<Tuple> tuples,
            List<String> arguments, Integer partitionFieldIndex) {
        ArrayList<ArrayList<Tuple>> partitionBuffers = new ArrayList<ArrayList<Tuple>>();
        int numPartitions = Integer.parseInt(arguments.get(0));
        int numTuples = tuples.size();

        // Determine partition sizes
        for (int i = 0; i < numPartitions; i++) {
            partitionBuffers.add(new ArrayList<Tuple>());
        }

        int[] partitionSizes = new int[partitionBuffers.size()];
        for (int i = 0; i < numTuples; i++) {
            partitionSizes[i % partitionSizes.length]++;
        }

        // Partition
        for (int i = 0, index = 0; i < numPartitions; i++) {
            int numberAdded = 0;
            while (index < numTuples) {
                partitionBuffers.get(i).add(tuples.get(index));
                index++;
                numberAdded++;
                if (numberAdded >= partitionSizes[i]) {
                    break;
                }
            }
        }
        return partitionBuffers;
    }

}
